﻿Imports System.Collections
Namespace AppDomains.Control
    Public Class Broadcaster
        Private Shared FInstance As Broadcaster = Nothing
        Private listeners As ListenerCollection
        Protected Sub New()
            listeners = New ListenerCollection
        End Sub
        Protected Shared ReadOnly Property Instance() As Broadcaster
            Get
                If (FInstance Is Nothing) Then
                    FInstance = New Broadcaster
                End If
                Return FInstance
            End Get
        End Property
        Public Shared Function Add(ByVal listener As Interfaces.IListener) As Integer
            Return Instance.listeners.Add(listener)
        End Function
        Public Shared Sub Remove(ByVal listener As Interfaces.IListener)
            Instance.listeners.Remove(listener)
        End Sub
        Public Shared Sub Broadcast(ByVal format As String, ByVal ParamArray args() As Object)
            Broadcast(String.Format(format, args))
        End Sub
        Public Shared Sub Broadcast(ByVal message As String)
            Broadcast(message, New GenericFormatter)
        End Sub
        Public Shared Sub Broadcast(ByVal message As String, ByVal formatter As Interfaces.IFormatter)
            Dim listener As Interfaces.IListener
            For Each listener In Instance.listeners
                If (listener.Listening) Then
                    listener.Listen(message, formatter)
                End If
            Next
        End Sub
    End Class
    Public Class ListenerCollection
        Inherits CollectionBase
        Default Public Property Item(ByVal index As Integer) As Interfaces.IListener
            Get
                Return (CType(List(index), Interfaces.IListener))
            End Get
            Set(ByVal Value As Interfaces.IListener)
                List(index) = Value
            End Set
        End Property
        Public Function Add(ByVal value As Interfaces.IListener) As Integer
            Return List.Add(value)
        End Function
        Public Sub Remove(ByVal value As Interfaces.IListener)
            List.Remove(value)
        End Sub
    End Class
    Public Class GenericFormatter
        Implements Interfaces.IFormatter
        Public Function ApplyFormatting(ByVal text As String) As String Implements Interfaces.IFormatter.ApplyFormatting
            Return text
        End Function
    End Class
End Namespace
Namespace Interfaces
    Public Interface IListener
        ReadOnly Property Listening() As Boolean
        Sub Listen(ByVal message As String, ByVal adname As String)
        Sub Listen(ByVal message As String, ByVal formatter As IFormatter)
    End Interface
    Public Interface IFormatter
        Function ApplyFormatting(ByVal text As String) As String
    End Interface
End Namespace